package com.lau.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.lau.constant.CacheConstants;
import com.lau.security.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Data
@Component
@ConfigurationProperties(prefix = "lau.jwt")
public class JwtUtils {

    //token有效期
    private int expire;
    private long overdue;
    //密钥
    private String secret;
    private String header;

    protected static final long MILLIS_MINUTE = 60 * 1000;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 从数据声明生成令牌
     * 生产的令牌没有过期时间
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }


    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(CacheConstants.LOGIN_USER_KEY, token);
        return generateToken(claims);
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        String userAgentHeader = ServletUtil.getHeader(request, "User-Agent", (String) null);
        UserAgent userAgent = UserAgentUtil.parse(userAgentHeader);
        //loginUser.setIpaddr(ip);
        //loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expire * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisUtil.set(userKey, loginUser, expire, TimeUnit.MINUTES);
    }

    // 解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        if (shouldRefreshAccessToken(loginUser.getExpireTime()))
            refreshToken(loginUser);
    }

    /**
     * 判断是否临期
     *
     * @param expireTime 超期时间
     * @return
     */
    private boolean shouldRefreshAccessToken(long expireTime) {
        long currentTime = System.currentTimeMillis();
        // 获取过期时间差
        long remainingTime = expireTime - currentTime;
        // 判断是否快要超期
        return remainingTime < overdue*1000;
    }

    public String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }
}
